library(tidyverse)
library(PlackettLuce)
library(broom)

set.seed(20250416)

dataLong = read_delim("rankings.txt")

modelData = dataLong %>% 
  group_by(question) %>% 
  nest %>% 
  mutate(data = map(data,
                    ~ rankings(.x,
                               id = "respondent",
                               item = "answer",
                               rank = "rank")),
         model = map(data,
                     PlackettLuce))


modelEstimates = modelData %>% 
  mutate(summary = map(model,
                       summary,
                       ref = NULL),
         summary = map(summary,
                       coef),
         summary = map(summary,
                       as_tibble,
                       rownames = "answer")) %>% 
  select(summary) %>% 
  unnest(summary) %>% 
  ungroup %>% 
  rename(estimate = Estimate,
         se = `Std. Error`,
         z = `z value`,
         p = `Pr(>|z|)`) %>% 
  mutate(upr = estimate + 1.96 * se,
         lwr = estimate - 1.96 * se)

plotTable = modelEstimates %>% 
  group_by(question) %>% 
  nest %>% 
  mutate(plot = map2(data,
                     question,
                     ~ .x %>% 
                       ggplot(aes(reorder(answer, 
                                          estimate, 
                                          decreasing = T), 
                                  estimate))+
                       geom_point(position = position_dodge2(width = .1))+
                       geom_errorbar(aes(ymin = lwr, 
                                         ymax = upr),
                                     position = position_dodge2(width = .1),
                                     width = .1)+
                       geom_hline(yintercept = 0,
                                  lty = 3)+
                       scale_x_discrete(name = NULL)+
                       scale_y_continuous(name = "log(Worth)")+
                       ggtitle(.y)+
                       theme_bw()+
                       theme(axis.text.x = element_text(angle = 320,
                                                        hjust = 0))))


cairo_pdf(filename = "pl.pdf",
          onefile = T,
          width = 6,
          height = 4)
plotTable %>%
  pluck("plot")
dev.off()
